import dotenv from "dotenv";
import { MongoClient } from "mongodb";
import { fileURLToPath } from "url";
import path from "path";

// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 加载环境变量
dotenv.config({ path: path.join(__dirname, "../.env") });

const MONGODB_URI = process.env.MONGODB_URI;
const DB_NAME = process.env.DB_NAME || "login-system";

// 初始化面单使用记录集合
async function initWaybillUsage() {
  let client;

  try {
    // 连接数据库
    client = new MongoClient(MONGODB_URI);
    await client.connect();
    console.log("数据库连接成功");

    const db = client.db(DB_NAME);

    // 创建面单使用记录集合
    const collections = await db
      .listCollections({ name: "waybill_usage" })
      .toArray();
    if (collections.length === 0) {
      await db.createCollection("waybill_usage");
      console.log("创建面单使用记录集合成功");

      // 创建索引
      await db
        .collection("waybill_usage")
        .createIndex({ customerId: 1, shopId: 1, expressCompany: 1 });
      await db.collection("waybill_usage").createIndex({ usageDate: -1 });
      console.log("创建索引成功");
    } else {
      console.log("面单使用记录集合已存在");
    }

    console.log("初始化完成");
  } catch (error) {
    console.error("初始化失败:", error);
  } finally {
    if (client) {
      await client.close();
      console.log("数据库连接已关闭");
    }
    process.exit(0);
  }
}

// 运行初始化
initWaybillUsage();
